<template>
    <div class="product-content">
      <!-- 骨架屏加载效果 -->
      <div v-if="loading" class="product-skeleton">
        <div style="padding: 20px;">
          <div class="skeleton-breadcrumb"></div>
        </div>
        <div class="pro-box">
          <div class="pro-lyt-left">
            <div class="product-gals-box">
              <div class="skeleton-image-container">
                <div class="skeleton-image"></div>
                <div class="skeleton-image"></div>
                <div class="skeleton-image"></div>
                <div class="skeleton-image"></div>
              </div>
            </div>
          </div>
          <div class="pro-lyt-right">
            <div class="skeleton-info">
              <div class="skeleton-name"></div>
              <div class="skeleton-title"></div>
              <div class="skeleton-price"></div>
              <div class="skeleton-reviews"></div>
              <div class="skeleton-promotion"></div>
              <div class="skeleton-color"></div>
              <div class="skeleton-size"></div>
              <div class="skeleton-qty"></div>
              <div class="skeleton-button"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实际内容 -->
      <template v-else>
        <!--  面包屑  -->
        <div style="padding: 20px;">
          <a-breadcrumb separator="/">
            <a-breadcrumb-item
                v-for="(item, index) in props.detailData?.breadcrumbs || []"
                :key="index"
                @click="item.type === 1 ? handleBreadcrumbClick(item.url) : null"
                style="cursor: pointer"
            >
              {{ item.name }}
            </a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        <div class="pro-box">
            <div class="pro-lyt-left">
                <div class="product-gals-box">
                    <div class="product-gals-box" v-for="(group, color, index) in colorNameList" :key="color" v-show="color === selectedColor">
                        <div v-for="item in group" :key="item.id" class="carousel-item" 
                             @click="handleImageClick(item)"
                             @mousemove="handleMouseMove"
                             @mouseleave="handleMouseLeave">
                            <img :src="item.image" :alt="color" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="pro-lyt-right">

              <div class="product-title">
                  <div class="product-title-top">
                      <div class="product-title-top-title">{{localDetailData.name}}</div>
                  </div>
                 
                  <div class="product-title-bottom">
                      <div class="visit-count" style="display: flex;align-items: center;"><img style="width: 20px;height: 20px; margin-right: 5px;" :src="SVG_ICONS.Visit" /><div>{{visitCount==0?visitCount: localDetailData.visit}}</div></div>
                  </div>
                  <div class="good_price">
                      <span class="price">{{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(colorPrice)}}</span>
                      <span class="old-price" v-if="localDetailData.discount_enabled == 1"><span style="text-decoration: line-through;">{{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(calculateOriginalPrice(localDetailData)) }}</span></span>
                  </div>
                  <div class="good_price">
                      <span class="good-price__discount" style="margin: 0px" v-if="localDetailData.discount_enabled == 1">-{{ localDetailData.discount || 0 }}%</span>
                      <span class="goods-points">Earn {{ points }} lannuan Points</span>
                  </div>
              </div>

                <!-- <span class="itemcode">#2245334343412</span> -->

               
                <div class="boxColorSize" v-for="(item,index) in spec_list" :key="index">
                  <div class="color-picker" v-if="item.name=='color' || item.name=='Color'">
                      <!-- 上半部分颜色显示 -->
                      <div class="color-display">
                        <span class="color-label">{{item.name}}: </span>
                        <span class="color-value">{{selectedColor }}</span>
                      </div>
                      <!-- 下半部分图片 -->
                      <div class="clothes-container">
                        <div
                          v-for="(item, index) in skuColor"
                          :key="index"
                          class="clothes-item"
                          :class="{ active: currentSelection === index }"
                          @click="switchSlide(index,item)"
                        >
                          <img :src="item.color" class="clothes-image" />
                        </div>
                      </div>
                  </div>
                  <!-- 尺寸 -->
                  <div class="size-box"  v-if="item.name=='Size'|| item.name=='size'">
                      <div class="size" >
                        

                         <div v-if="detailData.size_list" class="sizeTable" style="cursor: pointer;" @click="sizeChart">
                          Size Guide
                          </div>
                          <!-- <div style="sizeCharttxt">Size Chart</div> -->
                      </div>

                          <a-select
                              v-model:value="sizeId"
                              placeholder="Select Size"
                              :style="{
                                  
                                  '--ant-primary-color': '#000',
                                  '--ant-text-color-placeholder': '#000',
                                  '--ant-input-icon-color': '#000',
                                  'width': '65%'
                              }"
                          >
                              <a-select-option
                                  v-for="item in skuListSize1"
                                  :key="item.id"
                                  :value="item.id"
                              >
                                  {{ item.size }}
                              </a-select-option>
                          </a-select>
                      <div class="Tips" v-if="!sizeId">Tips:Please choose a size</div>
                  </div>
                </div>
                <!-- 数量Qty -->
                <div class="QTY">
                    <!-- <div class="QTY-title">Qty:</div> -->
                    <div class="QTY-content">
                        <a-input-number
                          placeholder="Select QTY" 
                          v-model:value="Qty"
                          :min="1"
                          :max="100"
                          :step="1"
                          :style="{
                              '--ant-primary-color': '#000',
                              '--ant-text-color-placeholder': '#000',
                              '--ant-input-icon-color': '#000',
                              'width': '65%',
                              'border': 'none',
                              'border-bottom': '1px solid #000',
                              'border-radius': '0'
                          }"
                          class="qty-input-no-arrows"
                        />
                    </div>
                    <!-- price -->
                    <!-- <div class="price-box">
                        <span class="total"> Total price:</span><span class="price"> {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(colorPrice * Qty) }}</span>
                    </div> -->
                    <!-- ADD购物车 -->
                    <div class="addCart" style="margin-top: 30px;">
                         <a-button class="cartBtn" type="primary" @click="AddCArt">
                           <span style="font-weight: 700; letter-spacing: 1px; font-size: 12px;">Add to bag</span>
                         </a-button>
                    </div>
                    <!-- <div style="margin: 10px 0;"><img v-for="(item,index) in 5" :key="index" style="width: 20px;height: 20px; margin-right: 2px;" :src="SVG_ICONS.Xing" /> <span class="reviews-number">（{{localDetailData.evaluate_count}} Reviews ）</span></div> -->
                    <div style="margin: 30px 0;"><img v-for="(item,index) in 5" :key="index" style="width: 20px;height: 20px; margin-right: 2px;" :src="SVG_ICONS.Xing" /> <span class="reviews-number">5 Stars</span></div>

                     <!-- 收藏 -->
                    <FavoriteButton v-model="localDetailData.favorite" :id = "localDetailData.id"/>
                    <!-- 分享 -->
                    <div class="share" @click="openShare">
                      <img  style="width: 15px;height: 15px;margin-right:5px" :src="SVG_ICONS.Fenxiang" />
                      Share
                    </div>
                    <div class="link-box" v-show="showShare">
                      <div class="title">Copy link</div>
                      <div class="link-boxs">
                        <div class="link">https://admin.lannuan.com/index.php/product/{{ detailData.url }}.html</div>
                        <img  style="width: 15px;height: 15px;margin-right:5px" :src="SVG_ICONS.copey" @click="copyLink(detailData.url)" />
                      </div>
                    </div>
                     <div class="promotion" style="font-weight: bold;">
                        <div>Free shipping</div>
                        <div> Free Shipping over {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(yunPrice) }}</div>
                    </div>
                    <div class="details">
                      <div class="details-title" v-if = "detailData.goods_detail">Details</div>
                      
                        <div class="title" v-html="renderedContent"></div>
                    </div>
                    <!-- <Delivery/> -->
                    <!-- <h2 class="section-title" v-if="!props.types">Complete the look</h2>
                    <Also :relatedGoods="relatedGoods" v-if="!props.types"/> -->
                    <!-- <h2 class="section-title" v-if="!props.types">Customers Also Bought</h2>
                    <Also :relatedGoods="hotGoods" v-if="!props.types"/> -->
                </div>
            </div>
        </div>
        <a-drawer
          v-model:visible="drawerVisible"
          :placement="placement"
          title="Size Table"
          width="900"
          @close="handleDialogVisible(false)"
        >
          <SizeTable @dialogVisible="handleDialogVisible" :sizeData = "detailData" />
        </a-drawer>
      </template>
    </div>
  </template>

  <script lang="ts" setup>
  import { ref ,computed, onMounted, watch ,toRaw,watchEffect,getCurrentInstance, nextTick, onUnmounted} from 'vue';
  import FavoriteButton from './favoriteButton.vue'
  import Also from './also.vue'
//   import Delivery from './delivery.vue'
  import { useCartStore } from '@/store/cart'
  import {addCarts,getCarts} from "@/api/details.ts";
  import { message, Modal, Drawer } from 'ant-design-vue'
  import mitt from '@/utils/mitt.ts'
  import { useCurrencyStore } from '@/store/currency'
  const currencyStore = useCurrencyStore()
  const cartStore = useCartStore()
  import {useRouter} from "vue-router"
  import SizeTable from './SizeTable.vue'
  import SVG_ICONS from "@/assets/SVG_ICONS.ts";
  import {Local, Session} from "@/utils/storage.ts";
  import emitter from '@/utils/eventBus';
  import MarkdownIt from 'markdown-it'
  const placement = ref('right');
  const drawerVisible = ref(false);
  const { proxy } = getCurrentInstance()
  const router = useRouter()
  const emit = defineEmits(['closeModal'])
  const props = defineProps({
    detailData: {
      type: Object,
      required: true,
    },
    visitCount: {
      type: Number,
      required: true,
    },
    relatedGoods: {
      type: Array,
      required: true,
    },
    hotGoods: {
      type: Array,
      required: true,
    },
    types: {
      type: Number,
      required: true,
    }
  })
  const showShare = ref(false)
  // 加载状态控制 - 确保最开始一定显示骨架屏
  const loading = ref(true)
  const hasShownSkeleton = ref(false) // 添加标记，记录是否已经显示过骨架屏
  const points = computed(() => {
  return Math.round(colorPrice.value / 10);
});
  const yunPrice = ref(99)
  const skuList = ref([])
  const skuColor = ref([])
  const skuSizeInfo = ref([]) // 新增尺寸信息存储
  const skuListSize = ref([]) //第一组尺寸
  const skuListSize1 = ref()
  const localDetailData = ref({})
  const spec_list = ref([])
  const sizeState = ref(true)
  const dialogTableVisible = ref(false)
  const colorImg = ref()
  const colorPrice = ref()
  const colorId = ref()
  const Qty = ref(1);
  const size = ref('');
  const sizeId = ref();
  const localDetailCart = ref()
  const colorNameList = ref({}) // 添加 colorNameList ref


const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true
})
  const renderedContent = computed(() => {
  console.log('Content:', props.detailData?.goods_detail)
  if (!props.detailData?.goods_detail) return ''
  return md.render(props.detailData.goods_detail)
})
  const calculateOriginalPrice = (image) => {
  if (image.discount_enabled && image.discount) {
    // 假设折扣是百分比，例如20表示8折
    const discountMultiplier = (100 - image.discount) / 100;
    return (image.min_price / discountMultiplier).toFixed(2);
  }
  return image.max_origin_price;
};
  // 创建一个函数用于关闭骨架屏
  const hideSkeletonWithDelay = () => {
    // 如果已经关闭了骨架屏，不再重复操作
    if (!loading.value) return;
    
    // 使用nextTick确保DOM已更新
    nextTick(() => {
      // 延迟关闭骨架屏，确保用户能看到过渡效果
      setTimeout(() => {
        loading.value = false;
        hasShownSkeleton.value = true; // 标记已显示过骨架屏
        console.log('骨架屏已关闭');
      }, 500);
    });
  };
  //分享隐藏
  const openShare = () => {
    showShare.value = !showShare.value
  }
  //复制
  const copyLink = (e: string) => {
    const link = `https://testadmin.frsst.com/index.php/product/${e}.html`
    navigator.clipboard.writeText(link)
    message.success('Copied to clipboard')
  }
  // 提取sku数据
  watchEffect(() => {
    if (localDetailData.value?.sku_list?.length) {
      // 有数据时处理逻辑
      const colorMap = new Map()
      const sizeData = []

      skuList.value = localDetailData.value.sku_list.map(sku => {
        const specs = sku.spec?.map(({ name, value }) => ({ name, value })) || []
        const colorValue = specs.find(s => s.name === 'color' || s.name === 'Color')?.value
        const sizeObj = specs.find(s => s.name === 'size' || s.name === 'Size')
        console.log('colorValue', colorValue)
        // 颜色处理逻辑（仅存储第一个ID）
        if (colorValue) {
          if (!colorMap.has(colorValue)) {
            colorMap.set(colorValue, {
              color: colorValue,
              previewImage: sku.image,
              firstId: sku.id , // 只存储第一个匹配的ID
              price:sku.price,
              color_name:sku.color_name
            })
          }
          // 不再更新已存在的颜色项
        }

        // 尺寸处理保持不变
        if (sizeObj?.value) {
          sizeData.push({ id: sku.id, size: sizeObj.value,color: specs[0].value})
        }

        return {color_name:sku.color_name, id: sku.id, image: sku.image, specs }
      })
      
      //将color_name里面相同的颜色的数据取出
      colorNameList.value =   skuList.value.reduce((acc, cur) => {
          const color = cur.color_name
          if (!acc[color]) {
            acc[color] = []
          }
          acc[color].push(cur)
          return acc
        }, {})
        console.log('colorNameList',colorNameList)
      // 按颜色分组计算属性
      console.log("skuList.value", skuList.value)
      console.log('colorMap', colorMap)
      skuColor.value = Array.from(colorMap.values()).map(c => ({
        color: c.color,
        previewImage: c.previewImage,
        id: c.firstId, // 重命名属性为id
        price: c.price,
        color_name: c.color_name
      }))
      console.log('skuColor', skuColor.value)
      const fistcolor = skuList.value?.[0]?.specs?.[0]?.value
      if (fistcolor) {
        skuSizeInfo.value = sizeData
        skuListSize1.value = skuSizeInfo.value.filter(item => item.color === fistcolor)
        if (skuColor.value.length > 0) {
          colorId.value = skuColor.value[0].id
          colorPrice.value = skuColor.value[0].price || localDetailData.value.max_price
          selectedColor.value = skuColor.value[0].color_name
        }
      }
      
      // 数据处理完成后关闭骨架屏
      hideSkeletonWithDelay();
    } else if (Object.keys(localDetailData.value || {}).length > 0) {
      // 有数据但没有sku_list，也要关闭骨架屏
      hideSkeletonWithDelay();
    }
  })
  const sizeChart = () => {
    drawerVisible.value = true;
  }
  // 处理弹框显示和隐藏
  const handleDialogVisible = (visible) => {
    drawerVisible.value = visible;
  };

  watch(() => props.detailData, (newVal) => {
    // 只有在首次加载或数据变化且还没显示过骨架屏时才显示骨架屏
    if (newVal && !hasShownSkeleton.value) {
      loading.value = true;
      console.log('数据发生变化，显示骨架屏');
      
      try {
        // 数据处理
        localDetailData.value = JSON.parse(JSON.stringify(toRaw(newVal) || {}))
        
        // 检查数据完整性
        if (Object.keys(localDetailData.value).length > 0) {
          colorPrice.value = localDetailData.value.max_price || 0;
          spec_list.value = localDetailData.value.spec_list || [];
          
          if (spec_list.value && spec_list.value.length > 0) {
            sizeState.value = spec_list.value.some(item => item.name === 'Size' || item.name === 'size');
          }
          
          updateTabsListFavorites();
          
          // 如果没有sku_list，在这里关闭骨架屏
          if (!localDetailData.value?.sku_list?.length) {
            hideSkeletonWithDelay();
          }
        } else {
          // 数据为空，也关闭骨架屏
          hideSkeletonWithDelay();
        }
      } catch (e) {
        localDetailData.value = {};
        // 出错时也要关闭骨架屏
        hideSkeletonWithDelay();
        console.log('数据处理出错', e);
      }
    } else if (newVal && hasShownSkeleton.value) {
      // 如果已经显示过骨架屏，则不再显示，直接更新数据
      try {
        localDetailData.value = JSON.parse(JSON.stringify(toRaw(newVal) || {}))
        if (Object.keys(localDetailData.value).length > 0) {
          colorPrice.value = localDetailData.value.max_price || 0;
          spec_list.value = localDetailData.value.spec_list || [];
          updateTabsListFavorites();
        }
      } catch (e) {
        console.error('数据处理出错', e);
      }
    }
  }, { immediate: true })
  const updateTabsListFavorites = () => {
    try {
      const collectedItems = cartStore.getCollect();
      if (!collectedItems.data || !collectedItems.data.length) return;
      const isFavorited = collectedItems.data.some(collection => collection.goods_id === localDetailData.value.id);
      if (isFavorited) {
        localDetailData.value.favorite = true;
      } else {
        localDetailData.value.favorite = false;
      }
    } catch (error) {
      console.error('Failed to update the product collection status:', error);
    }
  }

  /// 倒计时逻辑
  const countdown = ref(400); // 10分钟
  const countdownHours = ref('00');
  const countdownMinutes = ref('00');
  const countdownSeconds = ref('00');
  const isCountdownVisible = ref(true) // 新增显示状态
  onMounted(() => {
    // 只在首次加载且没显示过骨架屏时才显示
    if (!hasShownSkeleton.value) {
      // 确保组件初始化时显示骨架屏
      loading.value = true;
      console.log('组件初始化，显示骨架屏');
    }
      
    const interval = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
        updateCountdown();
      } else {
        clearInterval(interval);
      }
    }, 1000);
    
    // 只有在localDetailData有数据时才尝试初始化
    if (localDetailData.value && Object.keys(localDetailData.value).length > 0) {
      if (
        localDetailData.value?.spec_list?.length > 1 &&
        localDetailData.value.spec_list[1].value?.length
      ) {
        size.value = localDetailData.value.spec_list[1].value[0].name
        colorPrice.value = localDetailData.value.max_price
        spec_list.value = localDetailData.value.spec_list
      }
    }
    
    // 不在这里通过setTimeout直接关闭骨架屏
    // 让数据流驱动骨架屏的关闭
  })
  const showHours = computed(() => parseInt(countdownHours.value) > 0)
  const showMinutes = computed(() => parseInt(countdownMinutes.value) > 0)
  const shouldShow = computed(() =>
    parseInt(countdownHours.value) > 0 ||
    parseInt(countdownMinutes.value) > 0 ||
    parseInt(countdownSeconds.value) > 0
  )
  function updateCountdown() {
    let hours = Math.floor(countdown.value / 3600);
    let minutes = Math.floor((countdown.value % 3600) / 60);
    let seconds = countdown.value % 60;

    countdownHours.value = padZero(hours);
    countdownMinutes.value = padZero(minutes);
    countdownSeconds.value = padZero(seconds);
  }
  function padZero(num) {
    return num.toString().padStart(2, '0');
  }

  // 轮播图控制相关
  const selectedIndex = ref(-1)
  const carouselRef = ref(null)
  const currentSlide = ref(0)
  const hoverIndex = ref(-1)
  const currentSelection = ref(0)  // 初始化未选中状态
  const skuSize = ref([])
  const selectedColor = ref(null)
  // const skuListSize1 = ref()
  // 切换幻灯片方法
  const switchSlide = (index, item) => {
    colorImg.value = item.color //图片
    colorId.value = item.id //id
    colorPrice.value = item.price  //价格
    selectedColor.value = item.color_name
    sizeId.value = ''
    //在skuSizeInfo里取出有对应这个图片的数据
    skuListSize1.value = skuSizeInfo.value.filter(sku =>
        sku.color === item.color
    )
    currentSelection.value = currentSelection.value === index ? -1 : index
  }
  // 设置默认选中的颜色
  watchEffect(() => {
    if (skuColor.value.length > 0 && !selectedColor.value) {
      selectedColor.value = skuColor.value[0].color_name
    }
  })
  const handleThumbClick = (index, item) => {
    colorImg.value = item.color
    // 找到对应的轮播图索引
    const targetIndex = skuList.value.findIndex(sku => sku.id === item.id)
    if (targetIndex !== -1) {
      currentSlide.value = targetIndex
      // 调用轮播图的切换方法
      carouselRef.value.goTo(targetIndex)
    }
  }
  // 监听轮播图切换事件
  const handleSlideChange = (currentIndex) => {
    currentSlide.value = currentIndex
    // 联动缩略图
    const currentItem = skuList.value[currentIndex]
    if (currentItem) {
      const thumbIndex = skuColor.value.findIndex(item => item.id === currentItem.id)
      if (thumbIndex !== -1) {
        currentSelection.value = thumbIndex
      }
    }
  }
  // 面包屑跳转
  const handleBreadcrumbClick = (url: string) => {
    console.log('url',url)
  if (url) {
    window.location.href = url;
  }
}
  // 激活状态计算
  const isActive = (index) => {
    return index === currentSlide.value || index === hoverIndex.value
  }
  //尺寸
  const value = ref('')
  const priceMoney = ref()
  //计算金额
  const formatPrice = (value) => {
    const numericValue = Number(value) || 0
    priceMoney.value = numericValue.toLocaleString('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    })
    return `${currencyStore.currentCurrency.unit}${numericValue.toLocaleString('en-US', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    })}`

  }
  const addCart = ref([])
  // 加入到购物车
  const AddCArt = async () => {
  size.value = skuListSize1.value.find(option => option.id === sizeId.value)?.size || ''
  localDetailCart.value = {
    goods_id: localDetailData.value.id,
    name: localDetailData.value.name,
    color: localDetailData.value.images[0],
  }
  const token = Local.get('user_token') ? true : false;
  if(token){
       if(sizeState.value && sizeId.value){
      //  cartStore.addItem({
      //   id: localDetailCart.value.goods_id,
      //   name: localDetailData.value.name,
      //   price: priceMoney.value?priceMoney.value:colorPrice.value,
      //   color: colorImg.value?colorImg.value:localDetailCart.value.color,
      //   size: size.value,
      //   sku_id:sizeId.value,
      //   qty: Qty.value,
      //   favorite:localDetailData.value.favorite
      // })
      const res = await addCarts({
        sku_id:sizeId.value,
        num:Qty.value,
      })
         if (res.code === 200) {

           console.log(props.types)
           if(props.types === 1){
              //关闭modal
              emit('closeModal',res.result.goods_id)
              //刷新页面
              console.log(props.types,res.result.goods_id)
            }
          const cartRes = await getCarts()
          if(cartRes.code === 200){

            message.success('Add to cart successfully')
            console.log(cartRes.result)
            Session.set('cartList', cartRes.result)
            mitt.emit('addCart', res.result.id)

          }else{
            message.error('Add to cart failed')
          }

        }
    }else if(!sizeState.value){
       cartStore.addItem({
        id: localDetailCart.value.goods_id,
        name: localDetailData.value.name,
        price: priceMoney.value?priceMoney.value:colorPrice.value,
        color: colorImg.value?colorImg.value:localDetailCart.value.color,
        size: size.value,
        sku_id:sizeId.value,
        qty: Qty.value,
        favorite:localDetailData.value.favorite
      })
      const res = await addCarts({
        sku_id:sizeId.value?sizeId.value:colorId.value,
        num:Qty.value,
      })
        if (res.code === 200) {
          // mitt.emit('addCart', res.result.id)
          const cartRes = await getCarts()
          if(cartRes.code === 200){

            message.success('Add to cart successfully')
            console.log(cartRes.result)
            Session.set('cartList', cartRes.result)
            mitt.emit('addCart', res.result.id)

          }else{
            message.error('Add to cart failed')
          }
        }else{
          message.error('error')
        }
    }else{
      message.error('Please choose a size.')
    }
  }else{
      // const loading = Modal.confirm({
      //   title: 'Loading',
      //   content: 'Please wait while we log you in...',
      //   onOk: async () => {
      //     await router.push('/login')
      //   },
      //   onCancel: () => {
      //     // Handle cancel
      //   },
      // })

    message.error('Please login.')
    router.push('/login')

  }




  }
  // // 添加缩略图切换相关的方法
  // const thumbScrollRef = ref(null)
  // const thumbScrollLeft = ref(0)
  // const thumbItemWidth = 79 // 每个缩略图的宽度（69px + 左右margin各5px）

  // const handleThumbPrev = () => {
  //   if (thumbScrollLeft.value > 0) {
  //     thumbScrollLeft.value -= thumbItemWidth
  //     thumbScrollRef.value.scrollLeft = thumbScrollLeft.value
  //   }
  // }

  // const handleThumbNext = () => {
  //   const maxScroll = thumbScrollRef.value.scrollWidth - thumbScrollRef.value.clientWidth
  //   if (thumbScrollLeft.value < maxScroll) {
  //     thumbScrollLeft.value += thumbItemWidth
  //     thumbScrollRef.value.scrollLeft = thumbScrollLeft.value
  //   }
  // }

  // 添加组件卸载时的处理，重置hasShownSkeleton状态
  onUnmounted(() => {
    // 重置骨架屏显示状态，确保下次打开时仍然显示骨架屏
    hasShownSkeleton.value = false;
    console.log('组件卸载，重置骨架屏状态');
  })

  const handleImageClick = (item) => {
    const carouselItem = event.currentTarget;
    if (carouselItem.classList.contains('zoomed')) {
        carouselItem.classList.remove('zoomed');
    } else {
        carouselItem.classList.add('zoomed');
    }
  }

  const handleMouseMove = (event) => {
    const carouselItem = event.currentTarget;
    if (carouselItem.classList.contains('zoomed')) {
        const rect = carouselItem.getBoundingClientRect();
        const x = ((event.clientX - rect.left) / rect.width) * 100;
        const y = ((event.clientY - rect.top) / rect.height) * 100;
        carouselItem.style.setProperty('--mouse-x', `${x}%`);
        carouselItem.style.setProperty('--mouse-y', `${y}%`);
    }
  }

  const handleMouseLeave = (event) => {
    const carouselItem = event.currentTarget;
    if (carouselItem.classList.contains('zoomed')) {
        carouselItem.classList.remove('zoomed');
    }
  }
  </script>

  <style lang="scss" scoped>
  /* 骨架屏样式 */
  .product-skeleton {
    width: 100%;
    
    .skeleton-breadcrumb {
      height: 24px;
      width: 200px;
      background-color: #f5f5f5;
      border-radius: 4px;
      margin-bottom: 20px;
      animation: skeleton-pulse 1.4s ease-in-out infinite;
    }
    
    .skeleton-image-container {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      justify-content: space-between;
      max-width: 100%;

      .skeleton-image {
        display: block;
        width: 550px;
        height: 770px;
        margin: 10px;
        background-color: #f5f5f5;
        border-radius: 4px;
        animation: skeleton-pulse 1.4s ease-in-out infinite;
      }
    }
    
    .skeleton-thumbnails {
      display: flex;
      margin: 10px 16px;
      .skeleton-thumbnail {
        width: 69px;
        height: 100px;
        margin: 0 5px;
        background-color: #f5f5f5;
        border-radius: 4px;
        animation: skeleton-pulse 1.6s ease-in-out infinite;
      }
    }
    
    .skeleton-info {
      padding: 0 20px;
      
      .skeleton-name, .skeleton-title, .skeleton-price, 
      .skeleton-reviews, .skeleton-promotion, .skeleton-color, 
      .skeleton-size, .skeleton-qty, .skeleton-button {
        background-color: #f5f5f5;
        border-radius: 4px;
        margin-bottom: 20px;
        animation: skeleton-pulse 1.4s ease-in-out infinite;
      }
      
      .skeleton-name {
        width: 130px;
        height: 30px;
        margin-bottom: 30px;
      }
      
      .skeleton-title {
        height: 30px;
        width: 80%;
      }
      
      .skeleton-price {
        height: 25px;
        width: 120px;
        margin-top: 10px;
      }
      
      .skeleton-reviews {
        height: 20px;
        width: 180px;
      }
      
      .skeleton-promotion {
        height: 63px;
        width: 100%;
        margin-top: 30px;
      }
      
      .skeleton-color {
        height: 70px;
        width: 400px;
        margin-top: 20px;
      }
      
      .skeleton-size {
        height: 90px;
        width: 65%;
      }
      
      .skeleton-qty {
        height: 38px;
        width: 65%;
      }
      
      .skeleton-button {
        height: 38px;
        width: 65%;
        border-radius: 30px;
      }
    }
  }

  @keyframes skeleton-pulse {
    0% {
      background-color: #f5f5f5;
    }
    50% {
      background-color: #ffffff;
    }
    100% {
      background-color: #f5f5f5;
    }
  }

  .breadcrumb {
    font-size: 14px;
    color: #606266;
    margin: 20px 0;
    width: 100%;
  }

  .breadcrumb-link {
    color: #606266;
    /* 灰色 */
    text-decoration: none;
    /* 去掉下划线 */
  }

  .breadcrumb-link:hover {
    font-weight: bold;
    /* 加粗 */
    text-decoration: underline;
    /* 下划线 */
  }
  .product-content {
      // max-width: 1300px;
      // min-width: 960px;

      // height:100px;
      margin: 0 auto;
      background-color: #fff; // 添加背景色确保内容可见
      .pro-box{
          width:100%;
          height:100%;
          display: flex;
      }
      .pro-lyt-left{
          width:70%;
          display: flex;
          .product-gals-box{
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            .carousel-item {
                width: calc(50% - 10px);
                aspect-ratio: 578 / 770;
                overflow: hidden;
                margin: 5px;
                cursor: zoom-in;
                position: relative;
                
                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    display: block;
                    transition: transform 0.3s ease;
                }

                &.zoomed {
                    cursor: zoom-out;
                    img {
                        transform: scale(2);
                        transform-origin: var(--mouse-x) var(--mouse-y);
                    }
                }
            }
          }
      }
      .pro-lyt-right{
        margin-left:60px;
          float: right;
          width: 30%;
          position: sticky;
          top: 20px; // 距离顶部的距离
          height: fit-content;
          max-height: calc(100vh - 40px); // 设置最大高度，避免超出视口
          overflow-y: auto; // 内容过多时可滚动
          padding-right: 20px; // 添加右侧内边距
          // 添加滚动条样式
          &::-webkit-scrollbar {
              width: 4px;
          }
          &::-webkit-scrollbar-thumb {
              background-color: #ddd;
              border-radius: 2px;
          }
          &::-webkit-scrollbar-track {
              background-color: #f5f5f5;
          }
      }
  }



  .pro-lyt-right{
      display: inline;
      font-weight: 400;
      font-size: .875rem;
      line-height: 1.5;
      margin-right: 10px;
  }
  .product-title{
    .product-title-top{
        display: flex;
        justify-content: space-between;
        .product-title-top-title{
            font-size: 1rem;
            font-weight: 500;
        }
    }

  }
  .itemcode{
      color: #999;
      font-size: .75rem;
      margin-left:10px;
  }
  .reviews-number {
      font-size: 16px;
      text-decoration: underline;
      
  }
  .good_price{
      display: flex;
      align-items: center;
      // justify-items: center;
      .price{
          font-size:14px;
          margin:10px 0;
      }
      .old-price{
          margin-left: 15px;
          color: #999;
      }
      .good-price__discount {
          display: block;
          height:20px;
          line-height: 20px;
          margin: 0 15px;
          background: #000;
          color: #fff;
          font-size: .75rem;
          padding: 2px 10px;
      }
      .goods-points{
              margin-left: 10px;
              color: #000;
              font-size: .75rem;
      }

  }
  
 
  .color-picker {
    width: 400px;
  //   padding: 20px;
  //   background: #f5f5f5;
    border-radius: 8px;
  }

  .color-display {
    margin-top: 10px;
    font-size: 14px;
    
  }

  .color-label {
    font-weight: 500;
    color: #333;
  }

  .color-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .clothes-containe::-webkit-scrollbar {
      display: none; /* 隐藏滚动条 */
  }
  .clothes-container {
    margin-top:10px;
    display: flex;
    flex-wrap:nowrap;
    // gap: 5px;
  }

  .clothes-item {
    width: 36px;
    height: 36px;
    cursor: pointer;
    border-radius: 50%;
    background: white; /* 添加白色背景 */
    border: 1px solid transparent;
    box-sizing: border-box; /* 确保边框不改变容器尺寸 */
    overflow: hidden; /* 隐藏放大溢出部分 */
    margin: 0 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .clothes-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  /* 修改交互效果 */

  .clothes-item.active .clothes-image {
    transform: scale(0.8); /* 缩小图片 */
  }
  .clothes-item.active {
    border-color: #000; /* 添加黑色边框 */
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  }



  .clothes-containers {
    max-width: 500px;
    margin: 10px 16px;
    display: flex;
    align-items: center;
    position: relative;
  }

  .thumb-list {
    display: flex;
    flex-wrap: nowrap;
    overflow: hidden;
    overflow-x: auto;
    overflow-y: hidden;
    padding-bottom: 8px;
    scroll-behavior: smooth;
    flex: 1;
  }

  .thumb-arrow {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    transition: all 0.3s;
    z-index: 1;

    &:hover {
      background-color: rgba(0, 0, 0, 0.1);
    }

    &.left {
      margin-right: 10px;
    }

    &.right {
      margin-left: 10px;
    }
  }

  .clothes-items {
    margin: 0 5px;
    background: white;
    border: 2px solid transparent;
    box-sizing: border-box;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;

    &:hover {
      border-color: #000;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);

      .clothes-images {
        // transform: scale(0.9);
      }
    }

    &.active {
      border-color: #000;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);

      .clothes-images {
        // transform: scale(0.9);
      }
    }
  }

  .clothes-images {
    width: 69px;
    height: 100px;
    // margin: 0 5px;
    background: white;
    object-fit: cover;
    border: 1px solid transparent;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  /* 修改交互效果 */

  .clothes-items.active .clothes-images {
    // transform: scale(0.9); /* 缩小图片 */
  }

  .clothes-items.active  {
    border-color: #000; /* 添加黑色边框 */
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  }


  /* 点击时更明显的反馈 */
  .clothes-items:active {
    // transform: scale(0.98);
  }

  //尺寸
  .size-box{
      margin:20px 0;
      .size{
          margin:5px 0;
          width: 65%;
        //   font-weight: 700;
          display: flex;
          justify-content: right;
          align-items: center;
          font-size: 16px;
          .sizeCharttxt{
            font-size:20px;
            font-weight: 300;
          }
          .sizeTable{

              color:#000;
              font-size: 14px;
              font-weight: 600;
              // margin-left: 10px;
              cursor: pointer;
            //   下划线效果
            text-decoration: underline;


          }
      }
      .Tips{
          color: #d41818;
          font-size: .75rem;
          margin: 5px 0;
          word-wrap: break-word;
          font-weight: 700;
      }
  }
  .QTY{

      font-weight: 700;
      .QTY-title{
          margin:5px 0;
           font-size: 16px;
      }
      .price-box{
          margin-top:30px;
          .total{
              color: #999;
              font-size:16px;
          }
          .price{
              color:#000;
              font-size:16px;
          }
      }
      .addCart{
          display: flex;
          align-items: center;
          margin: 10px 0;
          gap: 0;
          .cartBtn{
              display: inline-block;
              width:80%;
              height:38px;
              font-size:12px;
              color:#fff;
              background:#000;
              border-radius: 30px;
              padding:5px  40px;
              font-weight: 900;
              border: none;
              &:hover{
                  background:#fff;
                  color:#000;
                  border: 1px solid #000;
               }
          }
      }

      .visit-count{
        display: flex;
        justify-content: left;
        margin: 10px 0;
        align-items: center;
        font-size:16px;
        font-weight: 700;
      }
  }
  :deep(.ant-carousel) {
    height: 100%;
    background-color: #fff;
    position: relative;
  }

  .share{
    font-size:12px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: underline;
    margin: 10px 0;
  }
  .link-box{
    .title{
      font-size:15px;
      font-weight: 600;
      margin: 10px 0;
    }
    .link-boxs{
      display: flex;
      padding-bottom:10px;
      border-bottom:1px solid #000;
    }
    .link{
      font-size:10px;
      margin-right:5px;
      cursor: pointer;
      // 超出省略号
       // 超出省略号
       overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .promotion{
      width:100%;
      // height:63px;
      // padding:5px 15px;
      // background: #e8e8e8;
      // box-sizing: border-box;
      margin-top: 15px;
      color: #666;
      font-size: .875rem;
      
  }
  .custom-arrow {
    width: 40px;
    height: 40px;
    background-color: #ddd9d3;
    border-radius: 50%;
    display: flex !important;
    align-items: center;
    justify-content: center;
    z-index: 1;
    cursor: pointer;
    transition: all 0.3s;
    opacity: 0;

    &:hover {
      background-color: #ddd9d3;
    }

    &.left {
      position: absolute;
      left: 20px;
      top: 50%;
      transform: translateY(-50%);
    }

    &.right {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .section-title {
    font-size: 16px;
    font-weight: 700;
    margin: 20px 0;
    text-align: left;
  }
  :deep(.ant-carousel .slick-prev) {
    left: 20px;
  }

  :deep(.ant-carousel .slick-next) {
    right: 20px;
  }

  :deep(.ant-carousel .slick-prev::before),
  :deep(.ant-carousel .slick-next::before) {
    display: none;
  }

  :deep(.ant-btn-primary) {
    background-color: #000;
    border-color: #000;
  }

  :deep(.ant-btn-primary:hover) {
    background-color: #333;
    border-color: #333;
  }

  :deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    box-shadow: none !important;
  }

  :deep(.ant-select-focused:not(.ant-select-disabled).ant-select:not(.ant-select-customize-input) .ant-select-selector) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    box-shadow: none !important;
  }

  :deep(.ant-input-number) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.ant-input-number:hover) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    box-shadow: none !important;
  }

  :deep(.ant-input-number-focused) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    box-shadow: none !important;
  }

  :deep(.ant-input-number-handler-wrap) {
    display: none !important; /* 隐藏上下箭头按钮 */
  }

  :deep(.ant-input-number-input) {
    border: none !important;
    // border-bottom: 1px solid #000 !important;
    background: transparent !important;
  }

  :deep(.ant-select-selector) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    background: transparent !important;
    border-radius: 0 !important;
  }

  :deep(.ant-select-selection-item) {
    border: none !important;
    background: transparent !important;
  }

  :deep(.ant-select-selection-placeholder) {
    border: none !important;
    background: transparent !important;
  }

  :deep(.ant-select-arrow) {
    color: #000 !important;
  }

  :deep(.ant-input-number-group-addon) {
    border: none !important;
    background: transparent !important;
  }

  :deep(.ant-input-number-group) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    background: transparent !important;
  }

  :deep(.ant-input-number-group-wrapper) {
    border: none !important;
    border-bottom: 1px solid #000 !important;
    background: transparent !important;
  }
  :where(.css-dev-only-do-not-override-12unj27).ant-btn-primary {
    color: #fff;
      background-color: #262626;
      box-shadow: none !important;
  
  }
  .qty-input-no-arrows {
    :deep(.ant-input-number-handler-wrap) {
      display: none !important;
    }
  }

  .details {
    
    .details-title{
      font-weight: 600;
      margin: 10px 0;
    }
      .title {
        list-style-type: none;
        margin-bottom: 4px;
        margin-left: -40px;
        font-size:13px;
        font-weight: 500;
       
      }
    
  }
  </style>